package com.sino.operation.service.business;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sino.operation.commons.ConstantValue;
import com.sino.operation.commons.commonEnum.StatusInfoEnum;
import com.sino.operation.dto.Dto;
import com.sino.operation.entity.*;
import com.sino.operation.param.inner.TaskCompletePublicParam;
import com.sino.operation.param.out.EscReciveByCounter;
import com.sino.operation.peripheral.esc.request.EscBody;
import com.sino.operation.peripheral.esc.request.NetHandle;
import com.sino.operation.util.PersistenceUtil;

import com.sino.operation.util.StringUtil;
import com.sino.operation.util.TimeUtil;
import com.sino.operation.vo.InnerTranceVo;
import com.sino.operation.vo.PublicInfo;
import com.sino.operation.vo.current.TaskOtherCompleteParam;
import lombok.extern.slf4j.Slf4j;


import java.util.*;

/**
 * @Title: Exec_710304
 * @Description:
 * @Author dengls
 * @date 2021/10/21 10:37
 */
@Slf4j
public class Exec_710304 extends  BaseAction {

    public Exec_710304(Map varMap, BizTranslist bizTranslist, SysAbMessage sysAbMessage, BizOperateLog bizOperateLog, Object registerTable, Object receiveParam) {
        super(varMap, bizTranslist, sysAbMessage,bizOperateLog, registerTable, receiveParam);
    }

    public Exec_710304(String journalNo,SysAbMessage sysAbMessage){
        super(journalNo,sysAbMessage);
    }
    @Override
    public PersistenceUtil executeReception() throws Exception {
        EscReciveByCounter receiveParam = (EscReciveByCounter) this.receiveParam;
        EscBody escBody = receiveParam.getEscBody();
        PublicInfo publicInfo = escBody.getPublicInfo();
        String json = JSONObject.toJSONString(receiveParam.getEscBody().getObject());
        InnerTranceVo innerTranceVo = JSONObject.parseObject(json, InnerTranceVo.class);
        String voucher_type = innerTranceVo.getVOUCHER_TYPE();//凭证类型
        log.info("流程发起报文:" + innerTranceVo.toString());
        String imageId = publicInfo.getImageId();//影像套号
        String tranCode = publicInfo.getTranCode();//交易码
        String businessType = publicInfo.getBusinessType();//业务类型
        String journalNo = this.bizTranslist.getJournalNo();
        BizInternalTrans  BizInternalTrans = new BizInternalTrans();

        // 判断走整单还是走切片(1表示走切片，2表示走整单).从报文中取出证明文件种类，若为77、78、80、81、99，则走整单，其他情况都走切片
        String[] ts = {"", "01", "18", "23", "38", "71", "72", "73", "77", "78", "80", "81", "99"};
        List<String> types = Arrays.asList(ts);
        // 验证证明文件种类是否正确
        if (voucher_type == null || !types.contains(voucher_type)) {
            return null;
        }

        String cps_flag = null;
        // 确定切片标志 放入流程变量 加入报文 更新登记簿表
        if (!"".equals(voucher_type) && Integer.valueOf(voucher_type.trim()) < 77) {
            cps_flag = "1";
        } else {
            cps_flag = "2";
        }
        innerTranceVo.setJournalNo(journalNo);
        escBody.setObject(innerTranceVo);
        receiveParam.setEscBody(escBody);
        BizInternalTrans.setJournalNo(journalNo);
        BizInternalTrans.setBsty(voucher_type);
        BizInternalTrans.setCpsFlag(cps_flag);
        BizInternalTrans.setImageId(imageId);
        BizInternalTrans.setTransCode(tranCode);
        BizInternalTrans.setBsty(businessType);
        this.bizTranslist.setSliceFlage(cps_flag);
        varMap.put("cps_flag", cps_flag);
        persistence.addEntity(BizInternalTrans);
        return persistence;
    }

    //整单1提交方法
    public PersistenceUtil executeTotalEntry1() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        String json = JSON.toJSONString(receiveParam);
        this.sysAbMessage.setMessageTotal1(json);
        return persistence;
    }

    public PersistenceUtil executeTotalEntry2() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        String json = JSON.toJSONString(receiveParam);
        this.sysAbMessage.setMessageTotal2(json);
        return persistence;
    }

    //修正岗提交方法
    public PersistenceUtil executeFixed() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        String json = JSON.toJSONString(receiveParam);
        String sliceFlage = bizTranslist.getSliceFlage();
        String journalNo = bizTranslist.getJournalNo();
        BizInternalTrans bizInternalTrans = bizInternalTransMapper.selectById(journalNo);
        Map<String, Map> infoInputs = receiveParam.getInfoInputs();
        bizInternalTrans= Exec_710304_Util.CollectionHandle(infoInputs, bizInternalTrans);//归集登记薄数据
        if (StatusInfoEnum.SLICE_FLAGE.getCode().equals(sliceFlage)) {
            this.varMap.put("cps_flag", StatusInfoEnum.SLICE_FLAGE.getCode());
        } else {
            this.varMap.put("cps_flag", StatusInfoEnum.TOTAL_FLAGE.getCode());
        }
        this.sysAbMessage.setMessageAuditing(json);
        this.sysAbMessage.setMessage(json);//
        persistence.addEntity(bizInternalTrans);
        return persistence;
    }


    //验印岗1提交方法
    public PersistenceUtil executeVerify1() {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        TaskCompletePublicParam taskCompletePublicParam = receiveParam.getTaskCompletePublicParam();
        String completeMark = taskCompletePublicParam.getCompleteMark();
        if (completeMark.equals("4")) {
            String verifyReason = taskCompletePublicParam.getVerifyReason();
            String verifyReasonType = taskCompletePublicParam.getVerifyReasonType();
            this.bizOperateLog.setOperateType(verifyReasonType);
            this.bizOperateLog.setOperReason(verifyReason);
        }
        return persistence;
    }

    //验印岗2提交方法
    public PersistenceUtil executeVerify2() {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        TaskCompletePublicParam taskCompletePublicParam = receiveParam.getTaskCompletePublicParam();
        String completeMark = taskCompletePublicParam.getCompleteMark();
        if (completeMark.equals("4")) {
            String verifyReason = taskCompletePublicParam.getVerifyReason();
            String verifyReasonType = taskCompletePublicParam.getVerifyReasonType();
            this.bizOperateLog.setOperateType(verifyReasonType);
            this.bizOperateLog.setOperReason(verifyReason);
        }
        return persistence;
    }
    @Override
    public PersistenceUtil executeAuth() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        TaskCompletePublicParam taskCompletePublicParam = receiveParam.getTaskCompletePublicParam();
        String completeMark = receiveParam.getTaskCompletePublicParam().getCompleteMark();
        String json = JSON.toJSONString(receiveParam);
        this.bizTranslist.setBackFlag(completeMark);//保存提交标志
        if (ConstantValue.CONDITION_PASS.equals(completeMark)) {
            BizAddImage bizAddImage = new BizAddImage();
            bizAddImage.setId(StringUtil.getId());
            bizAddImage.setJournalNo(taskCompletePublicParam.getJournalNo());
            bizAddImage.setStartTeller(taskCompletePublicParam.getCenterTellerNo());
            bizAddImage.setStartTellerName(taskCompletePublicParam.getCenterTellerName());
            bizAddImage.setStartDate(TimeUtil.getStandardTime());
            bizAddImage.setState("0");//默认未补扫
            bizAddImage.setNoPassReason(taskCompletePublicParam.getReason());
            persistence.addEntity(bizAddImage);
        }
        this.sysAbMessage.setMessageAuth(json);
        this.varMap.put("auth_flag", "0");

        return persistence;
    }

    @Override
    public PersistenceUtil executeNetwork() throws Exception {
        return null;
    }

    @Override
    public PersistenceUtil executeBack() throws Exception {
        return null;
    }

    @Override
    public Dto executeGetTaskList(NetHandle netHandle){
        return new Dto();
    }

    @Override
    public PersistenceUtil executeTerminal() throws Exception {
        return null;
    }

    //修正岗获取
    public Object executeFixedTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }

    //验印岗获取
    public Object executeVerifyTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }
    @Override
    public Object executeTotalEntryTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }

    @Override
    public Object executeAuthTask() throws Exception {
        BizInternalTrans bizInternalTrans = bizInternalTransMapper.selectById(journalNo);
        Map<String, Map> otherFields = new HashMap<>();
        Map<String, Map> focusFields = new HashMap<>();
        Map<String, Map> authResult = new HashMap<>();
        QueryWrapper<BizDictSet> wrapper = new QueryWrapper<>();
        wrapper.eq("FIELD_TRANS_CODE", bizInternalTrans.getTransCode());
        wrapper.eq("FIELD_TRANS_TYPE", bizInternalTrans.getBsty());
        List<BizDictSet> dictSets = bizDictSetMapper.selectList(wrapper);//查询交易字段
        String messageTotal1 = sysAbMessage.getMessageTotal1();
        Map<String, Map> infoInputs = JSON.parseObject(messageTotal1, TaskOtherCompleteParam.class).getInfoInputs();
        Set<String> set = infoInputs.keySet();//中心录入字段
        String s = JSON.toJSONString(bizInternalTrans);
        Map map = JSON.parseObject(s, Map.class);
        for (BizDictSet dictSet : dictSets) {
            String fieldEg = dictSet.getFieldEg();
            String field = StringUtil.slashToFirstLetterUpper(fieldEg);//转小写
            if ("1".equals(dictSet.getFieldFocus())) {
                HashMap<String, Object> focusField = new HashMap<>();
                if (set.contains(fieldEg)) {
                    focusField.put("sourceFlag", ConstantValue.SOURCE_FlAG_CENTER);//中心录入
                } else {
                    focusField.put("sourceFlag", ConstantValue.SOURCE_FlAG_BRANCH);//网点录入
                }
                focusField.put("CHE", dictSet.getFieldCn());//中文名
                focusField.put("value", map.get(field));//值
                focusFields.put(fieldEg, focusField);
            } else {
                HashMap<String, Object> otherField = new HashMap<>();
                if (set.contains(fieldEg)) {
                    otherField.put("sourceFlag", ConstantValue.SOURCE_FlAG_CENTER);//中心录入
                } else {
                    otherField.put("sourceFlag", ConstantValue.SOURCE_FlAG_BRANCH);//网点录入
                }
                otherField.put("CHE", dictSet.getFieldCn());
                otherField.put("value", map.get(field));
                otherFields.put(fieldEg, otherField);
            }
        }
        authResult.put("otherFields", otherFields);
        authResult.put("focusFields", focusFields);
        return authResult;
    }

    @Override
    public PersistenceUtil executeCharge() throws Exception {
        return null;
    }
}
